<?php
/**
 * Created by PhpStorm.
 * User: krystal
 * Date: 2019/3/20
 * Time: 16:23
 */

namespace App\Http\Controllers\Api\v1\Order;

use App\Http\Controllers\Api\BaseController;
use App\Http\Controllers\Api\v1\Order\CheckOrderController;
use App\Exceptions\ApiException;
use App\Tools\Orders as OrdersLib;
use App\Models\Api\Goods;
use App\Models\Api\Orders;
use App\Models\Api\Recode;
use App\Models\Api\LanmeiCounselorProblem;
use App\Models\Api\LanmeiCourse;
use App\Models\Api\LanmeiFortune;
use App\Models\Api\LanmeiOrder;
use App\Models\Api\LanmeiOrderGoods;
use App\Models\Api\LanmeiUserAccount;
use App\Models\Api\LanmeiUserAccountRecord;



use Cache,DB;

/**
 * 统一下单相关接口
 * Class OrdersPay
 * @package
 */
class OrdersPayController extends BaseController
{
    /**
     * 获取一段时间的订单数量,进行折扣活动
     * @param array $map
     * @return bool|mixed
     */
    public function getOrderNum($map = [])
    {
        $order_type = (int)$map['order_type'] ?? 0;
        $OrderModel = new Orders();

        return $OrderModel->getTimeTypeNum($order_type);
    }

    /**
     * 统一下单入口
     * @param array $map ['order_type'=>订单类型,'trade_type'=>支付方式,'gid'=>商品ID|问答时对应问题ID|围观时对应答案ID,'openid'=>微信支付openID,'callback_url'=>网页支付回跳地址,'extend'=>扩展数据,用于存储和订单表一同事物写入(更新)数据]
     * @return array|response\Json
     * @throws ApiException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     * @throws exception\DbException
     * @throws \Exception
     */
    public function pay_unlock($map = [])
    {
        $order_type = $map['order_type'];
        $trade_type = $map['trade_type'];
        $time = time();
        $uid = $request->uid;

        $gid = $map['gid'] ?? 0; // 商品ID | 问答时对应问题ID | 围观时对应答案ID
        //生时矫正下单参数
        $reid = $map['reid'] ?? 0;
        //运势下单参数
        $fid = 0;
        $rids = $map['rids'] ?? '';
        $start_time = $map['start_time'] ?? 0;//字符串类型
        $fortune_type = $map['fortune_type'] ?? 1;
        //地图下单参数
        $gids = isset($map['gids']) ? explode(',', $map['gids']) : '';
        $rid = $map['rid'] ?? 0;
        //视频下单参数
        $id = $map['id'] ?? 0;
        $openid = $map['openid'] ?? '';
        $callback_url = $map['callback_url'] ?? '';

        switch (true)
        {
            case $order_type == 1:
                $pay_des = '准吖 - 生时校正';
                $data = $this->pay_rec(['gid' => $gid, 'reid' => $reid]);
                $price = $data['price'];
                $type = 1;
                break;
            case in_array($order_type, [2, 3, 4]):
                $pay_des = '准吖 - 运势';
                $data = $this->pay_fortune(['gid' => $gid, 'rids' => $rids, 'start_time' => $start_time, 'fortune_type' => $fortune_type]);
                $price = $data['price'];
                $fid = $data['fid'];
                $type = 2;
                break;
            case $order_type == 5:
                $pay_des = '准吖 - 占星地图';
                $data = $this->pay_map(['gids' => $gids, 'rid' => $rid]);
                $price = $data['price'];
                $type = 3;
                break;
            case $order_type == 6:
                $pay_des = '准吖 - 占星视频';
                $data = $this->pay_video(['id' => $id]);
                $price = $data['price'];
                $gid = $data['gid'];
                $type = 4;
                break;
            case $order_type == 7:
                $pay_des = '准吖 - 占卜问答';
                $price = $map['extend']['counselor_price'];
                $type = 5;
                break;
            case $order_type == 8:
                $pay_des = '准吖 - 占星问答';
                $price = $map['extend']['counselor_price'];
                $type = 6;
                break;
            case $order_type == 9:
                $pay_des = '准吖 - 围观';
                $price = $map['extend']['price'];
                $type = 7;
                break;
            default :
                return show(config('code.error'), '下单商品信息有误,请重新下单');
        }
        // 生成唯一订单号  011806192149570386 01生时校正 02运势 03占星地图 04占星视频 05占卜 06占星 07围观
        $out_trade_no = createOrderNumber($type);

        // VIP 价格全部 0.01元
        $price = getVipPrice($uid, $price, $rid, $rids, $order_type);

        //新订单表生成数据
//        $this->insertNewOrder(['reid'=>$reid,'trade_type'=>$trade_type,'order_type'=>$order_type,'gctid'=>$gid,'gctids'=>$gids,'rid'=>$rid,'rids'=>$rids,'order_id'=>$out_trade_no,'total_amount'=>$price,'fortune_type'=>$fortune_type,'fortune_time'=>$start_time]);

        $price = sprintf('%.2f', $price);

        /**
         * $account int 下单使用的商户配置id
         * 支付方式   1=>支付宝，2=>微信支付，5=>京东支付，6=>微信公众号支付，7=>支付宝手机网页支付，8=>微信H5网页支付
         */
        $account = getAccountId($trade_type);

        // 生成订单到数据库
        try
        {
            DB::beginTransaction();

            $OrderModel = new Orders();
            // 组合订单表数据
            $insert = [
                'order_type' => $order_type,
                'uid' => $uid,
                'gid' => $gid,
                'order_id' => $out_trade_no,
                'reid' => $reid,
                'fid' => $fid,
                'trade_type' => $trade_type,
                'total_amount' => $price,
                'create_time' => $time,
                'status' => 0,
                'account' => $account
            ];
            // 订单表写入
            $oid = $OrderModel->insertGetId($insert);
            $res = true;
            // 其他类型订单处理
            switch ($type)
            {
                case 1: // 生时校正
                    break;
                case 2: // 运势
                    break;
                case 3: // 占星地图
                    $res = $this->addInfo($oid, $gids, $rid);
                    break;
                case 4: // 占星视频
                    break;
                case 5: // 问答--占卜
                    // 更新问答信息
                    $map['extend']['order_id'] = $out_trade_no;
                    $res = (new LanmeiCounselorProblem)->problemUpdate($map['extend']);
                    break;
                case 6: // 问答--占星
                    // 更新问答信息
                    $map['extend']['order_id'] = $out_trade_no;
                    $res = (new LanmeiCounselorProblem)->problemUpdate($map['extend']);
                    break;
                case 7: // 围观
                    break;
            }
            // 事物提交
            if ($oid && $res === true)
            {
                DB::commit();
            } else
            {
                DB::rollback();
            }
        }
        catch (\Exception $e)
        {
            DB::rollback();
            \Log::info($e->getMessage());
            throw new ApiException('订单入库失败,请重新操作', 200, config('code.error'));
        }

        // 删除订单缓存
        $OrderModel->rm_cache(['uid' => $request->uid, 'type' => 1, 'order_id' => $out_trade_no]);
        //开始写自己逻辑了

        if($trade_type == 3){
            $userInfoAcc =  (new LanmeiUserAccount())->getAccountInfoAndCreate($request->uid);

            if($price >=$userInfoAcc['balance']){
                throw new ApiException('余额不足请充值！', 200, config('code.error'));
            }
           $datax = [
                'balance' => bcsub($userInfoAcc['balance'] ,$price ,2),
            ];
           (new LanmeiUserAccount())->where(['uid' =>$request->uid])->update($datax); // 账户金额递增

             // 账户流水
            $recordData = [
                'order_id'=>$oid,
                'create_time' =>$time,
                'record_type' =>9,
                'gid' => $gid,
                'price' => $price,
                'balance' => bcsub($userInfoAcc['balance'] ,$price ,2),
                'account_id' => $userInfoAcc['uid'],
                'extend' => ''
            ];
           (new LanmeiUserAccountRecord())->create($recordData);

           (new Orders())->where(['id' => $oid, 'status' => 0])->update(['status' => 2]);
            $arr = [
                'status' => true,
                'data' => []
            ];

        }else{

            //支付订单
            $arr = (new OrdersLib())->unifyPayOrder(['trade_type' => $trade_type, 'total_amount' => $price, 'pay_des' => $pay_des, 'order_id' => $out_trade_no, 'openid' => $openid, 'callback_url' => $callback_url, 'order_type' => $order_type]);
        }


        if ($gid)
        {
            $skuId = 'pay_fortune_' . $gid;
        } else
        {
            $new_gid = [];
            foreach ($gids as $gid)
            {
                $new_gid[] = 'pay_fortune_' . $gid;
            }
            $skuId = implode(',', $new_gid);
        }

        $arr['data']['skuId'] = $skuId;

        return $arr;
    }

    /**
     * 生时矫正下单,获取商品信息
     * @param array $map
     * @return array|false|mixed|\PDOStatement|string|Model|response\Json
     * @throws ApiException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     * @throws exception\DbException
     */
    public function pay_rec($map = [])
    {
        //if (Cache::get($request->uid . ':pay:rec')) throw new ApiException('操作频繁,请稍候再试', 200, config('code.error'));
        Cache::set($request->uid . ':pay:rec', time(), 5);

        $gid = (int)$map['gid'];
        $id = (int)$map['reid'] ?? 0;// 商品id =>生时校正id


        $OrdersModel = new Orders();
        $GoodsModel = new Goods();

        //检测改生时矫正是否有未支付订单,有就删除该笔订单
        try
        {
            (new Orders())->where(['reid' => $id, 'status' => 0])->update(['is_del' => 1]);
        }
        catch (\Exception $e)
        {
            \Log::info('生时矫正下单修改未支付订单状态失败:' . $e->getMessage());
        }
        //检测改生时矫正是否有已支付订单，有就提示用户
        if ($OrdersModel->where(['reid' => $id, 'status' => 1])->first())
        {
            throw new ApiException('您已支付该笔订单，请查看订单。', 200, config('code.error'));
        }
        try
        {
            if ($this->is_apple_pay)
            {
                $goods = $this->apple_goods['rec_goods'];
            } else
            {
                // 商品金额信息
                $goods = $GoodsModel->getGoodsRec(['id' => $gid]);
            }

        }
        catch (\Exception $e)
        {
            return show(config('code.error'), '获取生时矫正商品信息失败');
        }
        //检测当前购买商品是否存在
        if (!$goods)
        {
            return show(config('code.error'), '商品不存在');
        }

        // 重组支付价格
        if (isset($goods['discount']) && $goods['discount'] > 0)
        {
            $price = $goods['or_prize'] * sprintf('%.2f', $goods['discount']);

        } else
        {

            $price = $goods['now_prize'];
        }

        $arr['price'] = $price;

        return $arr;
    }

    /**
     * 运势下单,获取商品信息
     * @param array $map
     * @return array|response\Json
     * @throws ApiException
     * @throws \Exception
     */
    public function pay_fortune($map = [])
    {
      /*  if (Cache::get($request->uid . ':pay:fortune')) throw new ApiException('操作频繁,请稍候再试', 200, config('code.error'));*/
        Cache::set($request->uid . ':pay:fortune', time(), 5);

        // 商品类型id   1=>生时校正
        $gid = (int)$map['gid'];
        // 选择的档案id，字符串
        $rids = $map['rids'];
        $arid = count(explode(',', $rids));
        // 选择的解锁日期,字符串类型
        $start_time = $map['start_time'];
        //运势类型id
        $fortune_type = $map['fortune_type'];

        $goods_model = new Goods();

        $test_time = explode('-', $start_time);

        $CheckOrders = new CheckOrderController();

        $fortuenTimeRange = config('fortune.fortune_time_range');
        //判断下单时间格式是否正确,获取下单时间的时间戳
        switch ($fortune_type)
        {
            case 1:
                if ($this->is_apple_pay)
                {
                    $goodes = $this->apple_goods['fortune_day_goods'];
                } else
                {
                    $goodes = $goods_model->getGoodsForDay(['id' => 2]);
                }

                if (count($test_time) !== 3) throw new ApiException('下单时间不符合格式,请重试', 200, config('code.error'));
                $year = $test_time[0];
                $month = $test_time[1];
                $day = $test_time[2];

                if (strlen($year) !== 4 || !in_array(strlen($month), [1, 2]) || !in_array(strlen($day), [1, 2]))
                {
                    throw new ApiException('下单时间不符合格式,请重试', 200, config('code.error'));
                }

                $date = $start_time;

                $dt = new \DateTime($date);

                $start_time = $dt->format('U');//获取时间戳

                break;
            case 2:
                if ($this->is_apple_pay)
                {
                    $goodes = $this->apple_goods['fortune_month_goods'];
                } else
                {
                    $goodes = $goods_model->getGoodsForMonth(['id' => 20]);
                }
                if (count($test_time) !== 2) throw new ApiException('下单时间不符合格式,请重试', 200, config('code.error'));
                $year = $test_time[0];
                $month = $test_time[1];

                if (strlen($year) !== 4 || !in_array(strlen($month), [1, 2]))
                {
                    throw new ApiException('下单时间不符合格式,请重试', 200, config('code.error'));
                }

                $date = $start_time . '-01-01';

                $dt1 = new \DateTime($date);

                $start_time = $dt1->format('U');//获取时间戳

                foreach ($goodes as $god)
                {
                    if ($god['id'] == $gid)
                    {
                        $dt2 = new \DateTime($date);
                        $dt2->modify($god['expire_time']);//加一天(只能是字符串类型)
                        $dt2->modify('-1 day');//加一天(只能是字符串类型)

                        $end_time = $dt2->format('U');//获取时间戳
                    }
                }
                $month_start_time = $fortuenTimeRange['month']['start'] . '-1 00:00:00';
                $month_end_time = $fortuenTimeRange['month']['end'] . '-31 23:59:59';
                $fortune_start_time = strtotime($month_start_time);
                $fortune_end_time = strtotime($month_end_time);

                break;
            case 3:
                if ($this->is_apple_pay)
                {
                    $goodes = $this->apple_goods['fortune_year_goods'];
                } else
                {

                    $goodes = $goods_model->getGoodsForYear(['id' => 24]);
                }

                $year = $test_time[0];

                if (strlen($year) !== 4)
                {
                    throw new ApiException('下单时间不符合格式,请重试', 200, config('code.error'));
                }

                $date = $start_time . '-01-01';

                $dt = new \DateTime($date);

                $start_time = $dt->format('U');//获取时间戳

                foreach ($goodes as $god)
                {
                    if ($god['id'] == $gid)
                    {

                        $dt2 = new \DateTime($date);

                        $dt2->modify($god['expire_time']);//加一天(只能是字符串类型)
                        $dt2->modify('-1 day');//加一天(只能是字符串类型)

                        $end_time = $dt2->format('U');//获取时间戳
                    }
                }

                $year_start_time = $fortuenTimeRange['year']['start'] . '-1-1 00:00:00';
                $year_end_time = $fortuenTimeRange['year']['end'] . '-12-31 23:59:59';
                $fortune_start_time = strtotime($year_start_time);
                $fortune_end_time = strtotime($year_end_time);

                break;
            default :
                $goodes = [];
                break;
        }

        //购买时间超出2018-2037提示用户不可购买
        if (isset($fortune_start_time, $fortune_end_time, $start_time, $end_time) && $fortune_start_time && $fortune_end_time && $start_time && $end_time)
        {
            if ($start_time < $fortune_start_time || $end_time > $fortune_end_time)
            {
                throw new ApiException('您购买的运势时间超出时间范围，请重新确认。', 200, config('code.error'));
            }
        }

        //检查当前档案是否已有当前订单
        $CheckOrders->check_fortunes(['rids' => $rids, 'start_time' => $start_time, 'gid' => $gid, 'fortune_type' => $fortune_type]);

        $goods = [];
        foreach ($goodes as $v)
        {
            if ($v['id'] == $gid)
            {
                $goods = $v;
            }
        }

        if (!$goods || empty($goods))
        {
            return show(config('code.error'), '商品不存在');
        }

        //检查是否在活动时间内,买一赠一
        $active = false;
        $fortuneData = ['rids' => $rids, 'start_time' => $start_time, 'goods' => $goods, 'active' => $active, 'fortune_type' => $fortune_type];
        //  将档案信息存入新表
        $fid = $this->addrecode($fortuneData);

        // 重组支付价格
        if (isset($goods['discount']) && $goods['discount'] > 0)
        {
            $price = $goods['or_prize'] * sprintf('%.2f', $goods['discount']);
        } else
        {
            $price = $goods['now_prize'];
        }

        //六一活动,获取活动价格
        $activeDiscount = active($map['gid'], $map['start_time']);
        if ($activeDiscount['discount'])
        {
            $price = sprintf('%.2f', $price * $activeDiscount['discount']);
        }

        $pay_price = $price * $arid;

        return [
            'fid' => $fid,
            'price' => $pay_price
        ];
    }

    /**
     * 占星地图下单,获取商品信息
     * @param array $map
     * @return float|int|response\Json
     * @throws ApiException
     */
    public function pay_map($map = [])
    {
        if (Cache::get($request->uid . ':pay:map'))
        {
            throw new ApiException('操作频繁,请稍候再试');
        }

        Cache::set($request->uid . ':pay:map', 1, 5);

        $gids = $map['gids'];// 商品类型id

        $rid = $map['rid'];// 档案id

        if (!$gids)
        {
            return show(config('code.error'), '请选择商品');
        }
        if (!$rid)
        {
            return show(config('code.error'), '请选择档案');
        }

        $CheckOrder = new CheckOrderController();
        $GoodsModel = new Goods();
        //检查是否有支付的订单,提示用户
        $CheckOrder->check_lines_pay(['rid' => $rid, 'gids' => $gids]);
        //检查是否有未支付的订单,删除重新下单
        $CheckOrder->check_lines(['rid' => $rid, 'gids' => $gids]);

        //获取商品信息
        try
        {
            if ($this->is_apple_pay)
            {
                $goods = $this->apple_goods['acg_goods'];
            } else
            {
                $goods = $GoodsModel->getGoodsForACG(['id' => 7]);
            }
        }
        catch (\Exception $e)
        {
            return show(config('code.error'), '商品未找到');
        }
        $goods = json_decode(json_encode($goods, true), true);

        $price = 0;
        $activeDiscount = false;
        // 重组支付价格
        foreach ($goods as $k => $v)
        {
            if (in_array($v['id'], $gids))
            {
                if (isset($goods['discount']) && $goods['discount'] > 0)
                {
                    $price += round($v['or_prize'] * $v['discount'], 2);

                } else
                    $price += round($v['now_prize'], 2);
                $activeDiscount = active($v['id']);
            }
        }
        if (!$price)
        {
            return show(config('code.error'), '商品不存在');
        }


        if ($activeDiscount['discount'])
        {
            $price = sprintf('%.2f', $price * $activeDiscount['discount']);
        }

        $arr['price'] = (string)$price;

        return $arr;
    }

    /**
     * 占星视频下单,获取商品信息
     * @param array $map
     * @return response\Json
     * @throws ApiException
     */
    public function pay_video($map = [])
    {
        if (Cache::get($request->uid . ':pay:video'))
        {
            throw new ApiException('操作频繁,请稍候再试');
        }

        Cache::set($request->uid . ':pay:video', 1, 5);

        $id = $map['id'];// 课程id

        $uid = $request->uid;

        //验证请求参数
        if (!$id)
        {
            return show(config('code.error'), '请选择购买的视频');
        }

        //检测当前id是否是已上架的视频
        $CourseModel = new LanmeiCourse();
        $course = $CourseModel->getCourseInfo(['id' => $id]);
        if (!$course)
        {
            return show(config('code.error'), '当前视频未上架,请重新选择');
        }
        //获取所有视频的商品信息
        $GoodsModel = new Goods();
        if ($this->is_apple_pay)
        {
            $goods_data = $this->apple_goods['video_goods'];
        } else
        {

            $goods_data = $GoodsModel->getVideoInfo(['id' => $course['gid']]);
        }

        if ($goods_data === false)
        {
            return show(config('code.error'), $GoodsModel->getError());
        }

        $goods = [];
        foreach ($goods_data as $good)
        {
            //获取当前视频的商品信息
            if ($good['id'] == $course['gid'])
            {
                $goods = $good;
            }
        }

        $CheckOrder = new CheckOrderController();
        //检查是否有有支付的订单,提示用户
        $CheckOrder->check_prepaid_video(['uid' => $uid, 'gid' => $course['gid']]);
        //检查是否有未支付的订单,将订单原有订单删除
        $CheckOrder->check_unpaid_video(['uid' => $uid, 'gid' => $course['gid']]);

        // 重组支付价格
        if (isset($goods['discount']) && $goods['discount'] > 0)
        {
            $price = (float)($goods['or_prize'] * $goods['discount']);

        } else
        {

            $price = $goods['now_prize'];
        }

        $arr['price'] = $price;
        $arr['gid'] = $goods['id'];

        return $arr;

    }

    /**
     * 将购买运势的档案信息存入新表
     * @param array $map
     * @return int|string
     */
    public function addrecode($map = [])
    {
        $rids = $map['rids'];
        $start_time = $map['start_time'];
        $fortune_type = $map['fortune_type'];

        $arr = [
            'type' => $fortune_type,
            'rids' => $rids,
            'time' => $start_time,
            'create_time' => time(),
        ];
//        $extend = [];
        //若在活动时间内，买一增一
//        if ($active) {
//            $expire_time = $goods['expire_time'];
//            $time = intval(substr($expire_time, 1, 1)) * 2;
//            $time_str = substr($expire_time, 2, 5);
//
//            $extend = ['expire_time' => '+' . $time . $time_str];
//            $extend = json_encode($extend, true);
//            $arr = [
//                'type' => $fortune_type,
//                'rids' => $rids,
//                'time' => $start_time,
//                'create_time' => time(),
//                'extend' => $extend,
//            ];
//        }

        //每日运势id

        return DB::table('fortune')->insertGetId($arr);

    }

    /**
     * 新建订单,生成中间表数据和命格线订单数据
     * @param $oid
     * @param $gids
     * @param $rid
     * @return bool|response\Json
     */
    public function addInfo($oid, $gids, $rid)
    {
        $array = [];
        foreach ($gids as $k => $v)
        {
            $array[] = [
                'gid' => $v,
                'oid' => $oid,
                'rid' => $rid
            ];
        }
        //中间表
        try
        {
            DB::table('orders_goods')->create($array);
        }
        catch (\Exception $e)
        {
            return show(config('code.error'), '下单数据生成失败,请重试');
        }

        return true;
    }

    //TODO 订单下单重构

    /**
     * 新表存入订单数据
     * @param array $param
     * @return bool|response\Json
     */
    private function insertNewOrder($param = [])
    {
        $reid = $param['reid'] ?? 0;
        $trade_type = $param['trade_type'];//支付方式
        $order_type = $param['order_type'] ?? 0;//商品id
        $gctid = $param['gctid'] ?? 0;//货品属性类型
        $gctids = $param['gctids'] ?? '';//货品属性类型,多个
        $rid = $param['rid'] ?? 0;//档案id
        $rids = $param['rids'] ?? '';//多个档案id
        $rids = explode(',', $rids);
        $order_id = $param['order_id'];
        $total_amount = $param['total_amount'];//支付价格

        $fortune_type = $param['fortune_type'] ?? 0;//运势类型1=>日运,2=>月运,3=>年运
//        $map_type = $param['map_type'] ?? 0;//地图类型1=>打包,2=>不打包
        $fortune_time = $param['fortune_time'] ?? '';//开通运势时间
        $uid = $request->uid;
        $now_time = time();
        $LanmeiOrder = new LanmeiOrder();
        $LanmeiOrderGoods = new LanmeiOrderGoods();

        //生成数据到新表
        //开启事务
        DB::beginTransaction();
        try
        {
            $insert = [
                'reid' => $reid,
                'uid' => $uid,
                'order_type' => $order_type,
                'order_id' => $order_id,
                'pay_type_id' => $trade_type,
                'total_amount' => $total_amount,
                'create_time' => $now_time,
                'status' => 0,
                'pay_status' => 0,
                'expire_time' => time() + 86400
            ];
            $oid = $LanmeiOrder->saveOrder($insert);

            $order_good = [];
            $save_fortune = true;
            switch ($order_type)
            {
                case 2:
                    foreach ($rids as $rid)
                    {
                        $order_good[] = [
                            'oid' => $oid,
                            'gctid' => $gctid,
                            'rid' => $rid
                        ];
                    }
                    $save_fortune = $this->saveFortune(['oid' => $oid, 'fortune_type' => $fortune_type, 'fortune_time' => $fortune_time]);
                    break;
                case 3:
                    foreach ($gctids as $gctid)
                    {
                        $order_good[] = [
                            'oid' => $oid,
                            'gctid' => $gctid,
                            'rid' => $rid
                        ];
                    }
                    break;
                default :
                    $order_good[] = [
                        'oid' => $oid,
                        'gctid' => $gctid,
                        'rid' => $rid
                    ];
                    break;
            }

            $order_good_status = $LanmeiOrderGoods->saveOrder($order_good);

            if ($oid && $order_good_status && $save_fortune)
            {
                DB::commit();
            } else
            {
                DB::rollback();
            }
        }
        catch (\Exception $e)
        {
            DB::rollback();

            return show(config('code.error'), '下单失败,请稍候重试');
        }
        return true;
    }


    /**
     * 保存运势记录
     * @param array $map
     * @return bool|response\Json
     */
    private function saveFortune($map = [])
    {
        $insert = [
            'oid' => $map['oid'],
            'fortune_status' => 0,
            'type' => $map['fortune_type'],
            'time' => strtotime($map['fortune_time']),
            'create_time' => time()
        ];

        $LanmeiFortune = new LanmeiFortune();

        try
        {
            $LanmeiFortune->insert($insert);
        }
        catch (\Exception $e)
        {
            return show(config('code.error'), '运势数据保存失败');
        }

        return true;
    }

}
